<template>
  <div class="body">
    <el-container style="height: 100%">
      <el-aside width="255px">
        <div
          class="flist"
          v-for="item in this.$store.state.talktoList"
          :key="item.userid"
        >
          <div @click="chat(item)">
            <el-avatar :src="item.userimg" :size="60"></el-avatar>
            <span style="width: 115px">{{ item.username }}</span>
          </div>
          <div class="close" @click="close(item)">
            <i class="el-icon-close"></i>
          </div>
        </div>
      </el-aside>
      <el-container>
        <el-main style="background-color: #f4f5f7">
          <div class="text-header">{{ this.talkto.username }}</div>
          <div class="text-main" id="text-main">
            <el-button type="text" class="load" v-if="more" @click="loadMore"
              >加载更多消息...</el-button
            >
            <div v-else class="load">没有更多消息了...</div>
            <div
              class="message"
              v-for="(item, index) in messageList"
              :key="index"
            >
              <div
                class="avatar"
                v-bind:class="{ avatar_right: isWho(item.fromid) }"
              >
                <el-avatar :src="whichImg(item.fromid)" :size="50"></el-avatar>
              </div>
              <div
                class="text"
                v-bind:class="{ text_right: isWho(item.fromid) }"
                style="white-space: pre-wrap"
                v-if="item.isImg === false"
              >
                {{ item.message }} <br />
                <div style="float: right">——{{ item.date }}</div>
              </div>
              <div
                class="img"
                v-else
                v-bind:class="{ img_right: isWho(item.fromid) }"
              >
                <img :src="item.message" style="width: 400px" />
              </div>
            </div>
          </div>
        </el-main>
        <el-footer height="310px">
          <div>
            <el-upload
              ref="upload"
              accept="image/jpeg,image/jpg,image/png,image/svg"
              :limit="1"
              :action="''"
              :with-credentials="true"
              :http-request="upimg"
            >
              <el-button
                type="primary"
                icon="el-icon-picture-outline"
                round
              ></el-button
            ></el-upload>
          </div>
          <div>
            <el-input
              type="textarea"
              v-model="text"
              rows="6"
              @keypress.native="event($event)"
            ></el-input>
            <el-button
              style="display: flex; float: right"
              @click="sendmsg"
              type="primary"
              >发送</el-button
            >
          </div>
        </el-footer></el-container
      >
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      more: true,
      talkto: {
        username: "",
        userid: "",
        userimg: "",
      },
      imgMsg: {
        toid: "",
        isImg: true,
        message: "",
        date: "",
      },
      text: "",
      // list: [],
      messageList: [],
      path:
        "ws://8.140.135.252:8080/socket/" + sessionStorage.getItem("userid"),
      socket: "",
    };
  },
  methods: {
    init() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        console.log("ok");
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.receivemsg;
      }
    },
    receivemsg(msg) {
      console.log(msg);
      var message = JSON.parse(msg.data);
      if (message.success == true) return;
      var s = {
        fromid: message.fromId,
        toid: message.toId,
        message: message.content,
        isImg: message.isImg,
        date: this.convertTime(message.sendTime),
      };

      console.log(s);
      if (s.fromid === this.talkto.userid) {
        if (s.isImg == true)
          s.message = "http://8.140.135.252:8080" + s.message;
        this.messageList.push(s);
        this.bottom();
      }
      this.storemsg(s);
    },
    sendM(msg) {
      var m = {
        toId: msg.toid,
        sendTime: Date.parse(new Date()),
        content: msg.message,
        isImg: msg.isImg,
      };
      this.socket.send(JSON.stringify(m));
    },
    open() {
      console.log("socket连接成功");
    },
    upimg(item) {
      const { file } = item;
      const formdata = new FormData();
      formdata.append("file", file);
      this.$http.post("upload/img/message", formdata).then((res) => {
        if (res.data.success === true) {
          var url = res.data.imgUrl;
          var message = {
            toid: this.talkto.userid,
            fromid: sessionStorage.getItem("userid"),
            message: url,
            date: this.convertTime(Date.parse(new Date())),
            isImg: true,
          };
          this.$refs["upload"].clearFiles();
          this.storemsg(message);
          this.sendM(message);
          message.message = "http://8.140.135.252:8080" + message.message;
          this.messageList.push(message);
          this.bottom();
        } else {
          this.$message.error("上传失败,请稍后重新上传!");
          this.$refs["upload"].clearFiles();
        }
      });
    },
    close(user) {
      this.$store.commit("popTalk", user);
    },
    chat(user) {
      //加载聊天记录
      //如果少于20,more:false
      this.talkto.username = user.username;
      this.talkto.userid = user.userid;
      this.talkto.userimg = user.userimg;
      this.messageList = this.getmsg(this.talkto.userid);
    },
    sendmsg() {
      if (this.text === "") {
        this.$message.error("请输入消息");
        return;
      }
      var message = {
        fromid: "",
        toid: "",
        message: "",
        date: "",
        isImg: false,
      };
      message.toid = this.talkto.userid;
      message.fromid = window.sessionStorage.getItem("userid");
      message.message = this.text;
      var timestamp = Date.parse(new Date());
      message.date = this.convertTime(timestamp);
      this.storemsg(message);
      this.sendM(message);
      this.messageList.push(message);
      this.bottom();
      this.text = "";
    },
    bottom() {
      var div = document.getElementById("text-main");
      setTimeout(() => {
        div.scrollTop = div.scrollHeight;
      }, 0);
    },
    whichImg(userid) {
      if (userid === this.talkto.userid) return this.talkto.userimg;
      else return window.sessionStorage.getItem("userimg");
    },
    isWho(userid) {
      if (userid === this.talkto.userid) return false;
      return true;
    },
    event(e) {
      if (e.ctrlKey) this.text += "\n";
      if (e.keyCode == 13) {
        this.sendmsg();
        e.preventDefault();
      } //禁止回车的默认换行
    },
    wrap() {
      this.text += "\n";
    },
    loadMore() {
      //加载更多消息
    },
    storemsg(message) {
      if (message == {}) return;
      var messageList = JSON.parse(
        localStorage.getItem("msg" + sessionStorage.getItem("userid"))
      );
      if (messageList === null) messageList = [];
      messageList.push(message);
      localStorage.setItem(
        "msg" + sessionStorage.getItem("userid"),
        JSON.stringify(messageList)
      );
    },
    getmsg(talktoid) {
      var messageList = JSON.parse(
        localStorage.getItem("msg" + sessionStorage.getItem("userid"))
      );
      if (messageList === null) {
        messageList = [];
        return [];
      }
      var list = [];
      for (var i = 0; i < messageList.length; i++) {
        if (
          messageList[i].fromid === talktoid ||
          messageList[i].toid === talktoid
        ) {
          list.push(messageList[i]);
        }
      }
      return list;
    },
    addtalk() {
      var msg = JSON.parse(
        localStorage.getItem("msg" + sessionStorage.getItem("userid"))
      );
      if (msg === null) return;
      for (var i = 0; i < msg.length; i++) {
        if (
          this.$store.state.talktoList.findIndex((item) => {
            item.userid === msg[i].fromid;
          }) == -1 &&
          this.$store.state.talktoList.findIndex(
            (item) => item.userid === msg[i].toid
          ) == -1
        ) {
          var id;
          if (msg[i].fromid === sessionStorage.getItem("userid")) {
            id = msg[i].toid;
          } else {
            id = msg[i].fromid;
          }
          console.log(id);
          this.$http.get("usr/info?uid=" + id).then((res) => {
            console.log(res.data);
            if (res.data.success === true) {
              var user = {
                userid: id,
                username: res.data.username,
                userimg: "http://8.140.135.252:8080" + res.data.iconUrl,
              };
              this.$store.commit("talkto", user);
            } else {
              this.$message.error("加载失败,请稍后再试!");
            }
          });
        }
      }
    },
    closeSocket() {
      console.log("close");
    },
    recieve(userid) {
      this.$http.get("my/message/unread?destId=" + userid).then((res) => {
        if (res.data.success === true) {
          if (res.data.messageList === []) return;
          var keymap = {
            fromId: "fromid",
            toId: "toid",
            sendTime: "date",
            content: "message",
          };
          for (var i = 0; i < res.data.messageList.length; i++) {
            var obj = res.data.messageList[i];
            for (var key in obj) {
              var newkey = keymap[key];
              if (newkey) {
                obj[newkey] = obj[key];
                delete obj[key];
              }
            }
          }
          var msg = JSON.parse(
            localStorage.getItem("msg" + sessionStorage.getItem("userid"))
          );
          for (var i = 0; i < res.data.messageList.length; i++) {
            msg.push(res.data.messageList[i]);
          }
          localStorage.setItem(
            "msg" + sessionStorage.getItem("userid"),
            JSON.stringify(msg)
          );
        }
      });
    },
    getunread() {
      this.$http.get("my/message/init").then((res) => {
        if (res.data.success === true) {
          console.log(res.data);
          console.log("1");
          var keymap = {
            fromId: "fromid",
            toId: "toid",
            sendTime: "date",
            content: "message",
          };
          for (var i = 0; i < res.data.messageList.length; i++) {
            var obj = res.data.messageList[i];
            for (var key in obj) {
              var newkey = keymap[key];
              if (newkey) {
                obj[newkey] = obj[key];
                delete obj[key];
              }
            }
          }
          var msg = JSON.parse(
            localStorage.getItem("msg" + sessionStorage.getItem("userid"))
          );
          if (msg === null) msg = [];
          for (var i = 0; i < res.data.messageList.length; i++) {
            msg.push(res.data.messageList[i]);
          }
          localStorage.setItem(
            "msg" + sessionStorage.getItem("userid"),
            JSON.stringify(msg)
          );
        } else {
          this.$message.error("加载失败,请稍后再试!");
        }
      });
    },
  },
  created() {
    // this.list = localStorage.getItem(sessionStorage.getItem("userid"));
    if (this.$store.state.talktoList.length >= 1) {
      this.talkto.username = this.$store.state.talktoList[0].username;
      this.talkto.userid = this.$store.state.talktoList[0].userid;
      this.talkto.userimg = this.$store.state.talktoList[0].userimg;
      this.getunread();
      this.addtalk();
      this.messageList = this.getmsg(this.talkto.userid);
    }
  },
  mounted() {
    var div = document.getElementById("text-main");
    div.scrollTop = div.scrollHeight;
    this.init();
  },
  destroyed() {
    // 销毁监听
    this.socket.close();
    this.socket.onclose = this.closeSocket;
  },
};
</script>


<style lang="less" scoped>
.body {
  background-color: #fff;
  height: 100%;
  width: 100%;
}
/deep/.el-aside {
  height: 100%;
}
/deep/.el-footer {
  background-color: #f4f5f7;
}
/deep/.el-aside .el-avatar {
  margin: 20px;
}
.flist {
  height: 100px;
  background-color: rgb(248, 246, 246);
  user-select: none;
}
.flist:hover {
  background-color: #e3e4e5;
}
.flist span {
  display: flex;
  float: left;
  font-size: 25px;
  height: 100%;
  line-height: 100px;
}
.active {
  background-color: #e3e4e5;
}
.text-header {
  width: 100%;
  height: 60px;
  font-size: 30px;
  text-align: center;
  line-height: 60px;
  border-bottom: 2px solid #d8d8d8;
}
.text-main {
  width: 100%;
  height: 485px;
  overflow-y: auto;
}
.message {
  overflow: hidden;
  position: relative;
  padding: 0 16px 16px 16px;
}
.text {
  background-color: #fff;
  display: inline-block;
  line-height: 30px;
  max-width: 500px;
  font-size: 20px;
  min-height: 60px;
  padding: 8px 16px;
  margin-left: 65px;
  word-wrap: break-word;
  border-radius: 0 20px 20px 20px;
}

.text_right {
  float: right;
  border-radius: 20px 0 20px 20px;
  margin-right: 65px;
}
.close {
  display: flex;
  float: right;
  height: 100%;
}
/deep/ .close i {
  line-height: 100px;
  margin-right: 20px;
}
/deep/.close i:hover {
  font-weight: 1000;
}
/deep/.el-main {
  border-bottom: 2px solid #d8d8d8;
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  padding: 0;
}
/deep/.el-footer {
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
}
/deep/.el-button.is-round {
  padding: 12px;
  margin: 12px;
}
/deep/.el-textarea__inner {
  font-size: 20px;
}
/deep/.message .el-avatar {
  margin: 0;
}
.avatar {
  display: inline-block;
  position: absolute;
  top: 0;
}
.avatar_right {
  right: 0;
}
.load {
  width: 100%;
  text-align: center;
  font-size: 16px;
  line-height: 40px;
}
.img {
  margin-left: 65px;
  float: left;
}
.img_right {
  margin-right: 65px;
  float: right;
}
</style>